package com.wlcb.jpower.chat.task.action;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlcb.jpower.chat.entity.customer.TblCustomerMsg;
import com.wlcb.jpower.chat.service.customer.CustomerMsgService;
import com.wlcb.jpower.constant.DBConstant;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.module.common.utils.Fc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: liwenfei
 */
@Slf4j
@Component("accessTask")
public class AccessTask {
    @Resource
    private CustomerMsgService customerMsgService;

    public void access() {
        log.info("开始清除未完成会话的用户Session time:{}",new Date().toLocaleString());
        //处理已经接入
        List<TblCustomerMsg> access = customerMsgService.list(new QueryWrapper<TblCustomerMsg>().lambda()
                .eq(TblCustomerMsg::getStatus, DBConstant.CustomerMsgEnum.ACCESSED.getType())
                .eq(TblCustomerMsg::getIsDeleted, 0));

        if (access.size() > 0) {
            List<TblCustomerMsg> accesses = new ArrayList<>();
            for (TblCustomerMsg msg : access) {
                ImChatRecordCache instance = ImChatRecordCache.getInstance(msg.getOpenid());
                TblCustomerMsg customerMsg = new TblCustomerMsg();
                customerMsg.setStatus(DBConstant.CustomerMsgEnum.WAIT_ACCESS.getType());
                customerMsg.setCurrentCid("");
                customerMsg.setId(msg.getId());
                accesses.add(customerMsg);
                if (!Fc.isNull(instance)) {
                    instance.removeCid();
                }
            }
            if (accesses.size() > 0) {
                customerMsgService.updateBatchById(accesses);
            }
        }
    }

}
